package com.example.musicrecorder;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ArrayList<String>songnames;
    int UPDATE = 0x101;
    private int count=0;
    private TextView name;
    int flag=1;
    //1:顺序
    //2:乱序
    //3:单曲循环
    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        songnames=new ArrayList<String>();
        name=findViewById(R.id.textView2);

        songnames.add("Rapbit - love letter (情书).mp3");
        songnames.add("封茗囧菌、洛少爷 - 胭脂妆.mp3");
        songnames.add("肥皂菌 - 万古生香.mp3");
        songnames.add("蒼井翔太 - BAD END.mp3");
        songnames.add("三无Marblue - 心生七面 善恶难辨.mp3");
        songnames.add("三无MarBlue - 深夜诗人.mp3");
        songnames.add("双笙(陈元汐) - 鸟语林.mp3");
        songnames.add("双笙(陈元汐)、易言、樊棋、南久 - 九九八十一.mp3");
        songnames.add("封茗囧菌、双笙(陈元汐) - 霜雪千年.mp3");
        songnames.add("迪玛希 - We Are One.mp3");





        Button start=findViewById(R.id.begin);
        MediaPlayer mediaPlayer=new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.release();
            }
        });
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {

        }
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    mediaPlayer.reset();
                    AssetManager assetManager=getAssets();
                    String sn=songnames.get(count);
                    AssetFileDescriptor assetFileDescriptor=assetManager.openFd(sn);
                    mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                            assetFileDescriptor.getStartOffset(),assetFileDescriptor.getLength());
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    String n=songnames.get(count);
                    String[] str2=n.split("-");
                    String str3=str2[1];
                    str3=str3.trim();
                    str3=str3.substring(0, str3.length()-4);
                    name.setText(str3);//设置当前播放名。
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        Button stop=findViewById(R.id.stop);
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                    stop.setText("继续");
                }
                else if(!mediaPlayer.isPlaying()){
                    mediaPlayer.start();
                    stop.setText("暂停");
                }
            }
        });


        Button sequence=findViewById(R.id.sequence);
        Button nonsequ=findViewById(R.id.nonsequence);
        Button loop=findViewById(R.id.loop);
        Button next=findViewById(R.id.next);
        Button before=findViewById(R.id.before);
        TextView textView=findViewById(R.id.textView);

        sequence.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag=1;
            }
        });

        nonsequ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag=2;
            }
        });

        loop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag=3;
            }
        });





        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.stop();
                mediaPlayer.reset();
                AssetManager assetManager = getAssets();
                AssetFileDescriptor assetFileDescriptor = null;
                if (flag == 1) {
                    try {
                        if (count == songnames.size() - 1) {
                            count = -1;
                        }
                        count++;
                        assetFileDescriptor = assetManager.openFd(songnames.get(count));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                }
                else if(flag==2){
                    try {
                        count=(int)(Math.random()*(songnames.size()-1));
                        assetFileDescriptor = assetManager.openFd(songnames.get(count));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                }
                else if(flag==3){
                    try {
                        assetFileDescriptor = assetManager.openFd(songnames.get(count));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                }
                String n=songnames.get(count);
                String[] str2=n.split("-");
                String str3=str2[1];
                str3=str3.trim();
                str3=str3.substring(0, str3.length()-4);
                name.setText(str3);//设置当前播放名。
            }
        });

        before.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.stop();
                mediaPlayer.reset();
                AssetManager assetManager=getAssets();
                AssetFileDescriptor assetFileDescriptor= null;
                if(flag==1) {
                    try {
                        if (count == 0) {
                            count = songnames.size();
                        }
                        count--;
                        assetFileDescriptor = assetManager.openFd(songnames.get(count));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                }
                else if(flag==2){
                    try {
                            count =(int)(Math.random()*(songnames.size()-1));
                        assetFileDescriptor = assetManager.openFd(songnames.get(count));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                }
                else if(flag==3){
                    try {
                        assetFileDescriptor = assetManager.openFd(songnames.get(count));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                }
                String n=songnames.get(count);
                String[] str2=n.split("-");
                String str3=str2[1];
                str3=str3.trim();
                str3=str3.substring(0, str3.length()-4);
                name.setText(str3);//设置当前播放名。
            }
        });

        ListView listView=findViewById(R.id.lv);
        ArrayList<Song>str=new ArrayList<Song>();
        Song song=new Song(songnames.get(0),0);
        str.add(song);
        Song song1=new Song(songnames.get(1),1);
        str.add(song1);
        Song song2=new Song(songnames.get(2),2);
        str.add(song2);
        Song song3=new Song(songnames.get(3),3);
        str.add(song3);
        Song song4=new Song(songnames.get(4),4);
        str.add(song4);
        Song song5=new Song(songnames.get(5),5);
        str.add(song5);
        Song song6=new Song(songnames.get(6),6);
        str.add(song6);
        Song song7=new Song(songnames.get(7),7);
        str.add(song7);
        Song song8=new Song(songnames.get(8),8);
        str.add(song8);
        Song song9=new Song(songnames.get(9),9);
        str.add(song9);


        mylist mylist=new mylist(str, this, R.layout.listviewitem);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tv=mylist.getView(i,view,listView).findViewById(R.id.songna);
                TextView tv2=mylist.getView(i,view,listView).findViewById(R.id.songid);
                try {
                    mediaPlayer.reset();
                    AssetManager assetManager=getAssets();
                    String sn=tv.getText().toString().trim();
                    count=Integer.valueOf(tv2.getText().toString().trim());
                    AssetFileDescriptor assetFileDescriptor=assetManager.openFd(sn);
                    mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                            assetFileDescriptor.getStartOffset(),assetFileDescriptor.getLength());
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    String n=songnames.get(count);
                    String[] str2=n.split("-");
                    String str3=str2[1];
                    str3=str3.trim();
                    str3=str3.substring(0, str3.length()-4);
                    name.setText(str3);//设置当前播放名。
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        listView.setAdapter(mylist);
        SeekBar seekBar=findViewById(R.id.toolbar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                Log.i("TAG:", "" + progress + "");
                int musicMax = mediaPlayer.getDuration(); //得到该首歌曲最长秒数
                int seekBarMax = seekBar.getMax();
                mediaPlayer.seekTo(musicMax * progress / seekBarMax);//跳到该曲该秒
                //autoChange = true;
                //manulChange = false;
            }
        });
        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {
                int mMax = mediaPlayer.getDuration();//最大秒数
                if (message.what==UPDATE) {
                    try {
                        seekBar.setProgress(message.arg1);
                        textView.setText(setPlayInfo(message.arg2 / 1000, mMax / 1000));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    seekBar.setProgress(0);
                    textView.setText("播放已经停止");
                }
                return false;
            }
        });
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                int position, mMax, sMax;
                while (!Thread.currentThread().isInterrupted()) {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        position = mediaPlayer.getCurrentPosition();//得到当前歌曲播放进度(秒)
                        mMax = mediaPlayer.getDuration();//最大秒数
                        sMax = seekBar.getMax();//seekBar最大值，算百分比
                        Message m = handler.obtainMessage();//获取一个Message
                        m.arg1 = position * sMax / mMax;//seekBar进度条的百分比
                        m.arg2 = position;
                        m.what = UPDATE;
                        handler.sendMessage(m);
                        //  handler.sendEmptyMessage(UPDATE);
                        try {
                            Thread.sleep(1000);// 每间隔1秒发送一次更新消息
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }


        };
        Thread t=new Thread(null,runnable,"t");
        t.start();

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.stop();
                mediaPlayer.reset();
                AssetManager assetManager = getAssets();
                AssetFileDescriptor assetFileDescriptor = null;

                if (flag == 1) {
                    try {
                        if (count == songnames.size() - 1) {
                            count = -1;
                        }
                        count++;
                        assetFileDescriptor = assetManager.openFd(songnames.get(count));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                }
                else if(flag==2){
                    try {
                        count=(int)(Math.random()*(songnames.size()-1));
                        assetFileDescriptor = assetManager.openFd(songnames.get(count));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                }
                else if(flag==3){
                    try {
                        assetFileDescriptor = assetManager.openFd(songnames.get(count));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                }
                String n=songnames.get(count);
                String[] str2=n.split("-");
                String str3=str2[1];
                str3=str3.trim();
                str3=str3.substring(0, str3.length()-4);
                name.setText(str3);//设置当前播放名。
            }
        });


    }
    private String setPlayInfo(int position, int max) {
        int pMinutes = 0;
        while (position >= 60) {
            pMinutes++;
            position -= 60;
        }
        String now = (pMinutes < 10 ? "0" + pMinutes : pMinutes) + ":"
                + (position < 10 ? "0" + position : position);

        int mMinutes = 0;
        while (max >= 60) {
            mMinutes++;
            max -= 60;
        }
        String all = (mMinutes < 10 ? "0" + mMinutes : mMinutes) + ":"
                + (max < 10 ? "0" + max : max);

        return now + " / " + all;
    }

}